package backend.toolkit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;

public class KeyStoreUtils {
    /**
     * Java密钥库(Java Key Store，JKS)KEY_STORE
     */
    private static final String KEY_STORE = "JKS";

    private static final String X509 = "X.509";

    /**
     * 从公钥文件当中读取公钥，公钥文件存储在设备某个特定位置
     *
     * @param publicKeyFilePath 公钥文件存放路径
     * @return
     */
    public static String loadPublicKey(String publicKeyFilePath) throws Exception {
        String publicKey = "";
        File file = new File(publicKeyFilePath);
        if (file.exists()) {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            publicKey = reader.readLine();
            // System.out.println("publicKey: " + publicKey);
            reader.close();
        } else {
            throw new RuntimeException("PublicKey File not exist!");
        }
        return publicKey;
    }

    /**
     * 从私钥文件当中读取私钥，私钥文件存储在我们自己的签名工具当中
     *
     * @param privateFilePath 私钥文件存储路径
     * @return
     */
    public static String loadPrivateKey(String privateFilePath) throws Exception {
        String privateKey = "";
        File file = new File(privateFilePath);
        if (file.exists()) {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            privateKey = reader.readLine();
            // System.out.println("privateKey: " + privateKey);
            reader.close();
        } else {
            throw new RuntimeException("PublicKey File not exist!");
        }
        return privateKey;
    }

    /**
     * 获得KeyStore
     *
     * @param keyStorePath
     * @param password
     */
    private static KeyStore getKeyStore(String keyStorePath, String password)
            throws Exception {

        FileInputStream is = new FileInputStream(keyStorePath);
        KeyStore ks = KeyStore.getInstance(KEY_STORE);
        ks.load(is, password.toCharArray());
        is.close();
        return ks;
    }

    /**
     * 由KeyStore获得私钥
     *
     * @param keyStorePath
     * @param alias
     * @param storePass
     */
    private static PrivateKey getPrivateKey(String keyStorePath, String alias, String storePass,
                                            String keyPass) throws Exception {
        KeyStore ks = getKeyStore(keyStorePath, storePass);
        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPass.toCharArray());
        return key;
    }

    /**
     * 由Certificate获得公钥
     *
     * @param keyStorePath KeyStore路径
     * @param alias        别名
     * @param storePass    KeyStore访问密码
     */
    private static PublicKey getPublicKey(String keyStorePath, String alias, String storePass)
            throws Exception {
        KeyStore ks = getKeyStore(keyStorePath, storePass);
        PublicKey key = ks.getCertificate(alias).getPublicKey();
        return key;
    }

    /**
     * 从KeyStore中获取公钥，并经BASE64编码
     *
     * @param keyStorePath
     * @param alias
     * @param storePass
     */
    public static String getStrPublicKey(String keyStorePath, String alias, String storePass)
            throws Exception {
        PublicKey key = getPublicKey(keyStorePath, alias, storePass);
        String strKey = Base64Utils.encode(key.getEncoded());
        return strKey;
    }

    /**
     * 获取经BASE64编码后的私钥
     *
     * @param alias
     * @param storePass
     * @param keyPass
     */
    public static String getStrPrivateKey(String keyStorePath, String alias, String storePass,
                                          String keyPass) throws Exception {

        PrivateKey key = getPrivateKey(keyStorePath, alias, storePass, keyPass);
        String strKey = Base64Utils.encode(key.getEncoded());
        return strKey;
    }

    public static void main(String args[]) throws Exception {
        // KeyStoreTool.loadPrivateKey("privateKey.txt");
        // KeyStoreTool.loadPublicKey("publicKey.txt");

        String publicKey = KeyStoreUtils.getStrPublicKey("appstore.keystore", "appstore", "123456");
        System.out.println("publicKey: " + publicKey);
        String privateKey = KeyStoreUtils.getStrPrivateKey("appstore.keystore", "appstore",
                "123456", "123456");
        System.out.println("privateKey: " + privateKey);
    }

}
